<?php 
class auth implements interface_auth {

    protected $session;
    protected $request;
    protected $permission = array();
    protected $user_type;
    protected $user_dao;

    public function __construct($request, $session, interface_user_dao $user_dao) {
        $this->request = $request;
        $this->session = $session;
        $this->user_type = $user_dao->get_user_type(); 
        $this->user_dao = $user_dao;

        if($this->is_logged()) { 
            $this->permission = $user_dao->get_permissions($this->get_user());
        }

    }
    
    public function set_token() {
        $this->session->data['token'] = md5(mt_rand());
    }

    public function validate_token(){
        if(isset($this->request->get['token'])) {
            if($this->request->get['token'] == $this->session->data['token']){
                return true;
            }
        }
        return false;
    }

    public function is_logged(){
        if(isset($this->session->data[$this->user_type])) {
            return true;
        }
        return false;
    }

    public function has_permission($key, $value) {
        if (isset($this->permission[$key])) {
            return in_array($value, $this->permission[$key]);
        }
        return false;
    }
   
    public function get_user_id(){
        return $this->session->data[$this->user_type];
    }

    public function get_user(){
       return $this->user_dao->get_by_id($this->get_user_id());
    }

    public function get_user_type(){
        return $this->user_type;
    }

    public function get_dao(){
        return $this->user_dao;
    }

    public function logout() {
        unset($this->session->data[$this->user_type]);
        $this->permission = array();
    }

    public function login($username, $password) {

        if($this->is_logged()){
            $this->logout();
        }

        $username = mb_strtolower($username, 'UTF-8');

        $user = $this->user_dao->login($username, $password);

        if(!$user instanceof interface_user) {
            return false;
        }

        $this->set_token();
        $this->session->data[$this->user_type] = $user->get_id();

        $this->permission = $this->user_dao->get_permissions($user);

        return true;
    }    

}
